$(function () {
    buildInitMenuTree();
    initEvent();
})

function buildInitMenuTree() {
    $.ajax({
        url: "/dms/resource/selectList",
        success: function(response){
            buildMenuTree(response);
        }
    });
}

function buildMenuTree(menus) {
    var fullMenus = [{"id":0,"type":1,"parentId":-1,"name":"根目录","open" : true}];
    fullMenus = fullMenus.concat(menus);
    for(var i = 0 ; i < fullMenus.length ; i++){
        var menu = fullMenus[i];
        if(menu.type == 1){//文件夹
            menu.iconSkin = " fa fa-folder ";
        }else if(menu.type == 2){//菜单
            menu.iconSkin = " iconfont icon-caidan2 ";
        }else if(menu.type == 3){//按钮
            menu.iconSkin = " iconfont icon-anniu5 ";
        }else if(menu.type == 4) {//接口
            menu.iconSkin = " iconfont icon-sj_url ";
        }
    }
    var opt = {
        isTree: true,
        rootId: 0,
        parentId: "parentId",
        children: "children",
        id: "id",
        name: "name",
        url: "url",
        sort: "sort",
        data: fullMenus,
        onclick: undefined,
    }
    initMenuTree(Tree.toTree(opt),-1);
}

function initMenuTree(zNodes,rootParentId) {
    var setting = {
        view: {
            sort:true,
            compareFunction: function(a,b){
                return a.hasOwnProperty('srot') && b.hasOwnProperty('srot') ? a['srot'] - b['srot'] : 0;
            },
            selectedMulti: false,
            showLine: false,
            showIcon: false,
            nameIsHTML: true
        },
        check: {
            enable: false
        },
        edit:{
          enable: true,
          showRemoveBtn: false,
          showRenameBtn: false,
        },
        data: {
            data : zNodes,
            simpleData: {
                enable : true,
                pIdKey : "parentId",
                rootPId:rootParentId
            }
        },callback : {
            beforeRemove: function(){return false;},
            beforeRename: function(){return false;},
            onClick: function(event,treeId,treeNode,clickFlag){
                var breadcrumb = ['<li class="breadcrumb-item">'+treeNode.name+'</li>'];
                var parentNode = treeNode.getParentNode();
                while (parentNode){
                    breadcrumb.push('<li class="breadcrumb-item">'+parentNode.name+'</li>');
                    parentNode = parentNode.getParentNode();
                }
                breadcrumb.reverse();
                $("#menu-breadcrumb").html(breadcrumb.join(""));
                if(treeNode.id == 0){
                  return;
                }
                $("#treeId").val(treeNode.tId);
                initMenuDetails(treeNode.id,treeNode.getParentNode().name);

            },
            //拖拽后调用
            onDrop : function (event, treeId, treeNodes, targetNode, moveType) {
                         var treeObj = $.fn.zTree.getZTreeObj(treeId);
                         var menus = [];
                         for(var i = 0 ; i < treeNodes.length ; i++){
                             var treeNode = treeNodes[i];

                             var parentNode = treeObj.getNodeByTId(treeNode.parentTId);
                             if(!parentNode){return ;}
                             var children = parentNode.children;
                             if(!children && !Array.isArray(children)){return ;}

                             for(var i = 0 ; i < children.length ; i++){
                                 var child = children[i];
                                 menus.push({id:child.id,parentId:child.parentId,sort:(i+1)});
                             }
                         }
                         $.ajax({
                             url : "/resource/move",
                             type:"post",
                             contentType:"application/json",
                             data:JSON.stringify(menus),
                             success: function(response){
                                 window.location.reload();
                             }
                         });
                     }
        }
    };
    $.fn.zTree.init($("#treeMenu"), setting, zNodes);
}

function initEvent() {
    $("#save").on("click",function () {
        var json = $("#menuForm").serializable();
        $.ajax({
            url : "/dms/resource/save",
            type:"post",
            contentType: "application/json",
            data : JSON.stringify(json),
            success: function(response){
                $.fn.currentBootstrapNavbar.reload();
            }
        });
    })

    $("#parentName").on("click",function () {
        var setting = {
            view: {
                sort:true,
                compareFunction: function(a,b){
                    return a.hasOwnProperty('srot') && b.hasOwnProperty('srot') ? a['srot'] - b['srot'] : 0;
                },
                selectedMulti: false,
                showLine: false,
                showIcon: false,
            },
            check: {
                enable: false
            },data: {
                simpleData: {
                    enable : true,
                    pIdKey : "parentId",
                    rootPId: -1
                }
            },
            callback : {
             onClick: function(event,treeId,treeNode,clickFlag) {
                 $("#parentId").val(treeNode.id);
                 $("#parentName").val(treeNode.name);
                 $('#parentName').dropdown('hide');
             }
            }
        };
        var nodes =  $.fn.zTree.getZTreeObj("treeMenu").setting.data.data;
        var ztree = $.fn.zTree.init($("#parentNameTree"), setting, nodes);
        var node = ztree.getNodeByTId($("#treeId").val());
        ztree.selectNode(node);
        $('#parentName').dropdown();
        $('#parentName').dropdown("show");
    });
}


function addHoverDom(treeId, treeNode) {
    var operatorEle = $("#" + treeNode.tId + "_span");
    if(treeNode.parentId == -1){
        var parent =  operatorEle.parent();
        parent.find(".edit").remove();
        parent.find(".remove").remove();
    }
    if (treeNode.editNameFlag || $("#addBtn_"+treeNode.tId).length > 0) return;
    var addStr = "<span class='button add' id='addBtn_" + treeNode.tId + "' title='添加' onfocus='this.blur();'></span>";
    operatorEle.after(addStr);
    var btn = $("#addBtn_"+treeNode.tId);
    if (btn){
        btn.bind("click", function(){
            beforeAdd(treeId,treeNode);
            return false;
        });
    }
}


function removeHoverDom(treeId, treeNode) {
    $("#addBtn_"+treeNode.tId).unbind().remove();
}



function beforeAdd(treeId, treeNode) {
    var zTree = $.fn.zTree.getZTreeObj("treeMenu");
    zTree.addNodes(treeNode, {pId:treeNode.id, name:"new node"});
    openMenuModel(1,treeNode.tid,treeNode.id,null,null);
   // var parentName = $(treeNode.name).text();
    //window.location.href = encodeURI("/pages/assist/menu/menu-edit.html?parentId="+treeNode.id+"&parentName="+parentName);
}

function beforeEditName(treeId, treeNode) {
      openMenuModel(2,treeNode.parentTId,treeNode.parentId,treeNode.tId,treeNode.id);
    //var parentNode = treeNode.getParentNode();
    //var parentName = $(parentNode.name).text();
    //window.location.href = encodeURI("/pages/assist/menu/menu-edit.html?id="+treeNode.id+"&parentId="+treeNode.parentId+"&parentName="+parentName);
    return false;
}

function beforeRemove(treeId, treeNode) {
    if(!treeNode.id){return true;}
    bootbox.confirm("确定删除吗?", function(result){
        if(result){
            $.ajax({
                url : "/resource/delete",
                type:"post",
                data:{id:treeNode.id},
                success: function(response){
                    var zTree =  $.fn.zTree.getZTreeObj("treeMenu");
                    zTree.removeNode(treeNode);
                    zTree.removeChildNodes(treeNode);
                }
            });
        }
    })
    return false;
}





/** type = 1 新增; type = 2 修改 */
function openMenuModel(type,ptid,pid,tid,id) {
    var options = {backdrop: 'static', keyboard: false};
    $('#menuModal').modal(options);
    if(pid == null){
        pid = 0;
    }
    $("#parentId").val(pid);
    initDictionary();
    initMenuDatails(id);
}



function initMenuDetails(id,parentName) {
    if(!id){return ;}
    $.ajax({
        url: "dms/resource/selectById?id="+id,
        success: function(menu){
            $("#menuForm").deserializable(menu);
            $("#menuForm #parentName").val(parentName);
        }
    });
}